// The Photo Hut Employee project runner. Builds, runs and destroys the required classes for implementing a proper Photo Hut Employee.

#include "../include/Employee.h"
#include "../include/Job.h"
#include "../include/PocoXMLParser.h"
#include <stdlib.h>
#include <cstring>

using namespace std;

int main (int argc, char *argv[]) {
	if (argc < 3) {
		std::cerr << "Usage: " << argv[0] << " host port" << std::endl;
		return -1;
	}
	std::string host = argv[1];
	short port = atoi(argv[2]);
	Employee* employee = new Employee(host, port);
	PocoXMLParser* xmlParser = new PocoXMLParser();
	Job* job;
	string xml;
	bool jobDeleted = false; // returns true if the built job was deleted
	if (!(employee->connect())) { // connect to server
		std::cerr << "Cannot connect to " << host << ":" << port << std::endl;
		delete employee;
		delete xmlParser;
		return 0;
	}
	while(1){
		if (!employee->getNewJob()) { // the employee asks the server for a new job, closes program if disconnected in the middle.
			cout << "Disconnected. Exiting...\n" << endl;
			break;
		}
		xml = employee->getXML();
		xmlParser->parseXmlString(xml);
		job = xmlParser->getParsedXML(); // parse the given xml job file and build an instance of Job accordingly
		jobDeleted = false;
		if (!employee->getImg(*job)) { // the employee asks the server for the job's photo, closes program if disconnected in the middle.
			break;
		}
		employee->processJob(*job); // the employee processes the photo according to the given job.
		if (!employee->sendImg(*job)) { // the employee sends the server the processes photo, closes program if disconnected in the middle.
			break;
		}
		delete job;
		jobDeleted = true;
		if (!(employee->reconnect())) { // the employee reconnects to the server.
			std::cerr << "Cannot connect to " << host << ":" << port << std::endl;
			break;
		}
	}
	delete employee;
	delete xmlParser;
	if (!jobDeleted) { // in case the job wasn't deleted because of a disconnection.
		delete job;
	}
	return 0;
}
